package com.sec.android.app.myfiles.facade.cmd;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;

import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.local.recent.RecentDbTableInfo;
import com.sec.android.app.myfiles.module.shortcut.ShortcutDbTableInfo;
import com.sec.android.app.myfiles.provider.DbTableInfo;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

public class RenameHomeItemCmd extends SimpleCommand {
    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();
        final Context context = (Context) params[0];
        FileRecord src = (FileRecord) params[1];
        FileRecord target = (FileRecord) params[2];

        if (src != null && target != null) {
            DbTableInfo tableInfo = getTableInfo(src.isDirectory());
            ContentValues values = new ContentValues();
            values.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.NAME), target.getName());
            StringBuilder where = new StringBuilder();
            String[] whereArgs;

            if (src.isDirectory()) {
                /** rename shortcut **/
                values.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH), target.getFullPath());
                FileRecord.StorageType storageType = src.getStorageType();
                where.append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE))
                        .append('=')
                        .append(FileRecord.ShortcutType.MyFiles.ordinal())
                        .append(" AND ")
                        .append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH))
                        .append("=? ");
                whereArgs = new String[]{src.getFullPath()};
            } else {
                /** rename recent files **/
                values.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.FILE_TYPE), MediaFile.getFileType(target.getFullPath(), context));
                where.append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.NAME))
                        .append("=?")
                        .append(" AND ")
                        .append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH))
                        .append("=?");
                whereArgs = new String[]{src.getName(), src.getPath()};
            }

            context.getContentResolver().update(Uri.parse(tableInfo.getUri()), values, where.toString(), whereArgs);
        }
    }

    private DbTableInfo getTableInfo(boolean isDirectory) {
        DbTableInfo retTableInfo;
        if (!isDirectory) {
            retTableInfo = RecentDbTableInfo.getInstance();
        } else {
            retTableInfo = ShortcutDbTableInfo.getInstance();
        }

        return retTableInfo;
    }
}
